
// dump [>[>] filename]  -> dump current fd to stdout
// dump buffer [>[>] filename] -> dump current fd to filename
// dump buffer slab_from[-to] slab_normal [>[>] filename]

void cmd_dump(istringstream &ss) {
  string bname="",slb="";
  bool usefile=false;
  ofstream ofl;
  string sff(ss.str());
  string fext;
  int red=sff.find('>');
  
  ss>>bname;
  
  if(red!=sff.npos) {
    if(sff.find(">>")!=sff.npos) { // append
      sff.erase(0,red+2);
      string fname=get_filename(remove_char(sff,' '));
      int dot=fname.find('.');
      if(dot!=fname.npos) fext=fname.substr(dot,100);
      ofl.open(fname.c_str(),std::ios_base::app);
      usefile=true;
    } else { // truncate
      sff.erase(0,red+1);
      string fname=get_filename(remove_char(sff,' '));
      int dot=fname.find('.');
      if(dot!=fname.npos) fext=fname.substr(dot,100);
      ofl.open(fname.c_str());
      usefile=true;
    }
  }
  
  if(bname!="") {
    
    string op("all");
    
    int at=bname.find('(');
    if(at!=bname.npos) {
      op=bname.substr(0,at);
      bname.erase(0,at+1);
      bname=remove_char(bname,"()");
    }
    
    // fixme: extension ".csv" and ".xyz" ".vtr" only for op=all
    
    istringstream bss(replace_char(bname,':',' '));
    bss>>bname;
    
    Buffer A; get_buffer(A,bname);
    if(A.empty) throw (string("can not find buffer: ")+bname).c_str();
    
    if(op=="all") {
      if(fext==".csv") { // comma separated
        if(usefile) A.dumpcsv(ofl);
        else A.dumpcsv(std::cout);
      } else if(fext==".xyz") { // xyz sparse
        if(usefile) A.dumpxyz(ofl);
        else A.dumpxyz(std::cout);
      } else if(fext==".vtr") {
        if(usefile) A.dumpvtr(ofl);
        else A.dumpvtr(std::cout);
      }
      else {
        if(usefile) A.dump(ofl);
        else A.dump(std::cout);
      }
    }
    
    else if(op=="slab") { // syntax: slab(buffer:from[:to[:normal]])
      int fr=0,to=0;
      char norm='z';      
      bss>>fr>>to>>norm;
      if(usefile) for(int i=fr;i<=to;i++) A.dump(ofl,i,norm);
      else for(int i=fr;i<=to;i++) A.dump(std::cout,i,norm);
    }
    
    else if(op=="profile") {
      char axis='z';
      bss>>axis;
      if(usefile) A.dump(ofl,axis);
      else A.dump(std::cout,axis);
    }
    
    else throw "unknown operation";
    
  } else {
    if(usefile) fd[current]->solver->Dump(ofl);
    else fd[current]->solver->Dump(std::cout);
  }
  
  if(usefile) ofl.close();
  
}
